package com.base.controller.coupon_api;

import com.base.comm.CommContent;
import com.base.helper.VosHelper;
import com.base.po.cfsp.UserBalance;
import com.base.po.cfsp.UserDeduct;
import com.base.po.cfsp_sdk.CFSPInfoUtil;
import com.base.po.coupon.PayOrderResponse;
import com.base.po.coupon.PayOrderResponseData;
import com.base.po.coupon.QueryOrderResponse;
import com.base.po.coupon.QueryStockResponse;
import com.base.po.coupon_prestore.CouponGoodsPrestore;
import com.base.po.coupon_prestore.CouponOrderPrestore;
import com.base.po.coupon_sdk.CouponInfoUtil;
import com.base.po.param.NetState;
import com.base.po.param.VosModelList;
import com.base.po.voip.ChangeRecord;
import com.base.po.voip.Subscribers;
import com.base.po.voip.Users;
import com.base.po.voip_coupon.CouponPayOrder;
import com.base.service.COUPON.CouponGoodsPrestoreService;
import com.base.service.COUPON.CouponOrderPrestoreService;
import com.base.service.COUPON.CouponPayOrderService;
import com.base.service.ChangeRecordService;
import com.base.service.LogsService;
import com.base.service.SubscribersService;
import com.base.service.UsersService;
import com.base.utils.GsonUtil;
import com.base.utils.IP;
import com.base.utils.Produce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 365优惠券(FSP扣币)
 *
 * @author K
 */
@RestController
@RequestMapping("/couponPay")
public class CouponPayForFspController {
    private final UsersService usersService;
    private final SubscribersService subscribersService;
    private final CouponGoodsPrestoreService couponGoodsPrestoreService;
    private final CouponPayOrderService couponPayOrderService;
    private final CouponOrderPrestoreService couponOrderPrestoreService;
    private final ChangeRecordService changeRecordService;
    private final LogsService logsService;

    @Autowired
    public CouponPayForFspController(UsersService usersService, SubscribersService subscribersService, CouponGoodsPrestoreService couponGoodsPrestoreService, CouponPayOrderService couponPayOrderService, CouponOrderPrestoreService couponOrderPrestoreService, ChangeRecordService changeRecordService, LogsService logsService) {
        this.usersService = usersService;
        this.subscribersService = subscribersService;
        this.couponGoodsPrestoreService = couponGoodsPrestoreService;
        this.couponPayOrderService = couponPayOrderService;
        this.couponOrderPrestoreService = couponOrderPrestoreService;
        this.changeRecordService = changeRecordService;
        this.logsService = logsService;
    }

    // 365优惠券扣币
    @RequestMapping(value = "/payForFsp", method = {RequestMethod.POST, RequestMethod.GET})
    public @ResponseBody
    NetState orderDetails(HttpServletRequest request, String parentId, String userId, String goodsId, Integer number) throws ParseException {
        NetState netState = new NetState();
        Users agent = usersService.selectByPrimaryKey(parentId);  // 代理商
        Subscribers user = subscribersService.selectByPrimaryKey(userId); // 用户
        CouponGoodsPrestore goods = couponGoodsPrestoreService.selectByPrimaryKey(goodsId);// 产品信息
        if (agent == null || agent.getDatastatus() == false
                || user == null || user.getDatastatus() == false
                || goods == null || goods.getDatastatus() == 0) {
            netState.setErrorCode(NetState.NODATA);
            netState.setData("参数异常或数据不存在");
            return netState;
        }

        // 变更前话费余额
        BigDecimal beforeB = new BigDecimal(0);
        //备注
        String remark = null;
        try {
            // TODO 暂时配注
            String userR = VosHelper
                    .GetVosAccount("{accounts:['" + agent.getAgentprefix() + user.getMobile() + "']}");
            if (userR != null) {
                VosModelList userR1 = GsonUtil.getObject(userR, VosModelList.class);
                if (userR1.retCode == 0) {
                    beforeB = userR1.infoCustomers[0].getMoney();
                } else {
                    beforeB = new BigDecimal(0);
                    remark = "暂无记录";
                }
            }
        } catch (Exception e) {
            beforeB = new BigDecimal(0);
            remark = "暂无记录";
        }
        //查询兑换者   变更前话费有效期
        Date beforeTimeB = user.getEndtime();
        // 查询兑换者   变更前购物金余额
        BigDecimal beforeS = BigDecimal.valueOf(user.getShopBalance());
        // 查询兑换者  变更前购物金有效期
        Date beforeTimeS = new SimpleDateFormat("yyyy-MM-dd").parse(user.getShopEnddate());
        // 变更话费金额
        BigDecimal changeB = new BigDecimal(0);
        // 变更购物金额
        BigDecimal changeS = new BigDecimal(0);
        // 查询充值者 变更后话费有效期
        Date changeTimeB = new Date();
        // 查询充值者 变更后购物金有效期
        Date changeTimeS = new Date();

        // 生成优惠券订单
        Double oriUnitPrice = goods.getOfficialprices();// 原始单价
        Double unitPrice = goods.getSaleprices();// 优惠单价
        try {
            // 查询商品库存
            QueryStockResponse stock = CouponInfoUtil.queryStock(goods.getId());
            if (stock != null && stock.getCode() == 200){
                if (number > stock.getData().getStock_num()){
                    netState.setErrorCode(NetState.FEAILED);
                    netState.setData("库存不足");
                    return netState;
                }
            }else {
                netState.setErrorCode(NetState.FEAILED);
                netState.setData("库存查询异常");
                netState.setJson(stock);
                return netState;
            }
        }catch (Exception e){
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("数据查询异常");
            return netState;
        }

        Double oriTotalPrice = oriUnitPrice * number;// 原始总价
        Double totalPrice = unitPrice * number;// 优惠总价
        // TODO 判断用户余额
        if (beforeB.compareTo(new BigDecimal(totalPrice)) == -1){
            netState.setErrorCode(NetState.FEAILED);
            netState.setData("用户话费余额不足");
            return netState;
        }
        // TODO 判断FSP用户余额
        UserBalance userBalance = CFSPInfoUtil.userBalance(user.getMobile());
        if (userBalance != null && userBalance.getCode() == 200){
            Double balance = Double.valueOf(userBalance.getData().getBalance());
            if (balance >= totalPrice){
                // 订单号
                String outTradeNo = Produce.getUUID(); // 主键ID
                // 初始化订单
                CouponPayOrder order = new CouponPayOrder(outTradeNo, agent.getId(), user.getId(), goods.getId(),
                        goods.getName(), oriUnitPrice, oriTotalPrice, unitPrice, totalPrice, number, (byte)0, Produce.getNowDate());

                int payOrderCode = payOrder(order);
                switch (payOrderCode){
                    case 200:
                        // TODO 判断FSP用户扣币
                        String note = "兑换优惠券:" + goods.getName() + ",件数:" + number;
                        UserDeduct userDeduct = CFSPInfoUtil.userDeduct(user.getMobile(), totalPrice, note);
                        if (userDeduct != null && userDeduct.getCode() == 200){
                            // 变更订单支付状态
                            order.setStatus((byte)1);
                            int orderCode = couponPayOrderService.insertSelective(order);
                            if (orderCode == 1){
                                changeRecord(request, user.getParentid(), user.getShopid(), user.getId(), user.getMobile(), totalPrice,
                                        beforeB, changeB, beforeS, changeS, beforeTimeB, changeTimeB, beforeTimeS, changeTimeS, remark);
                                netState.setErrorCode(NetState.SUCCESS_CONN);
                                netState.setData("扣币成功,优惠券兑换成功");
                            }else {
                                netState.setErrorCode(NetState.ERROR_OPERATE);
                                netState.setData("扣币成功,优惠券兑换失败,请联系客服");
                            }
                        }else {
                            netState.setErrorCode(NetState.SYSTEM_ERROR);
                            netState.setData("用户扣币异常");
                        }
                        break;
                    case 400:
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("优惠券生成失败");
                        break;
                    case 999:
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("优惠券生成异常");
                        break;
                    default:
                        netState.setErrorCode(NetState.SYSTEM_ERROR);
                        netState.setData("优惠券初始化失败");
                        break;
                }
            }else {
                netState.setErrorCode(NetState.ERROR_OPERATE);
                netState.setData("用户可用余额不足");
            }
        }else {
            netState.setErrorCode(NetState.SYSTEM_ERROR);
            netState.setData("用户数据异常");
        }

        return netState;
    }

    // 创建订单
    public int payOrder(CouponPayOrder order) {
        int code = 0;

        // 时间转换对象
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        // 创建订单id
        String payOrderId = order.getId();
        try {
            PayOrderResponse pay = CouponInfoUtil.payOrder(order.getProductid(), payOrderId, order.getNumber().toString());
            if (pay != null && pay.getCode() == 200){
                List<PayOrderResponseData> payOrders = pay.getData();
                for (PayOrderResponseData payOrder : payOrders){
                    CouponOrderPrestore couponOrder = new CouponOrderPrestore();
                    couponOrder.setId(payOrder.getOut_trade_no());
                    couponOrder.setOrderno(payOrder.getOrder_no());
                    couponOrder.setParentid(order.getParentid());
                    couponOrder.setUserid(order.getUserid());
                    couponOrder.setProductid(payOrder.getProduct_id());
                    couponOrder.setCardtype(payOrder.getCard_type());
                    couponOrder.setLinkurl(payOrder.getLink_url());
                    couponOrder.setUniquecode(payOrder.getUnique_code());
                    couponOrder.setCardno(payOrder.getCard_no());
                    couponOrder.setCardpwd(payOrder.getCard_pwd());
                    try {
                        couponOrder.setCouponcreatetime(dateFormat.parse(payOrder.getCreate_time()));
                    } catch (ParseException e) {
                        couponOrder.setCouponcreatetime(Produce.getNowDate());
                    }
                    couponOrder.setOrdercreatetime(Produce.getNowDate());
                    couponOrder.setOrderstatus(queryOrder(payOrder.getOrder_no()));
                    couponOrderPrestoreService.insertSelective(couponOrder);
                }
                code = 200;
            }else {
                code = 400;
            }
        }catch (Exception e){
            code = 999;
        }

        return code;
    }

    // 订单状态查询
    public int queryOrder(String orderNo){
        Integer orderStatus = null;

        QueryOrderResponse query = CouponInfoUtil.queryOrder(orderNo);
        if (query != null && query.getCode() == 200){
            orderStatus = query.getData();
        }

        return orderStatus == null ? -1 : orderStatus;
    }

    // 话费变更记录
    public void changeRecord(HttpServletRequest request, String parentId, String shopId, String userId, String mobile,
                             Double totalPrice, BigDecimal beforeB, BigDecimal changeB, BigDecimal beforeS, BigDecimal changeS,
                             Date beforeTimeB, Date changeTimeB, Date beforeTimeS, Date changeTimeS, String remark){
        Users agent = usersService.selectByPrimaryKey(parentId);
        // 变更话费金额
        changeB = BigDecimal.valueOf(totalPrice);
        // 话费有效期不变
        changeTimeB = beforeTimeB;
        VosHelper.PayVosAccount("{\"ownerName\":\"" + agent.getAgentprefix()
                + mobile + "\",\"ownerType\":\"2\",\"money\":\"-" + totalPrice
                + "\",\"memo\":\"兑换优惠券" + totalPrice + "元\"}");

        try {
            // 优惠券兑换变更记录
            changeRecordService.insertSelective(new ChangeRecord(parentId, shopId, userId, Produce.getNowDate(), beforeB, changeB, 0, beforeTimeB,
                    changeTimeB, "兑换优惠券", beforeS, changeS, 0, beforeTimeS, changeTimeS, "兑换优惠券", remark));
        } catch (Exception e) {
            logsService.insert(CommContent.TYPE_CREATE, mobile + "兑换优惠券变更记录异常", agent.getUsername(), true,
                    IP.getIpAddr(request));
        }
    }
}
